/*  请求案例  加入responseType为文件流  isNotTransformRequestResult告诉后台是否返回文件流
getList: (data) => {
  return $axios({
    url: '/xxx/xxx/xxx',
    method: 'post',
    data,
    responseType: 'blob', 
    isNotTransformRequestResult: true
  })
}
*/
import axios from "axios";
import { ElMessage } from "element-plus";

const $axios = axios.create({
  baseURL: import.meta.env.VITE_APP_BaseApi + import.meta.env.VITE_APP_PROXY,
  timeout: 300000, // request timeout 5 分钟
});

// 请求拦截
$axios.defaults.headers["Content-Type"] = "application/json;charset=utf-8";

$axios.interceptors.request.use((config) => {
  if (config.url !== "/login") {
    config.headers.Authorization = window.localStorage.getItem("token");
    config.headers["accessToken"] = window.localStorage.getItem("token");
  }
  return config;
});

// 响应拦截
$axios.interceptors.response.use(
  (response) => {
    let resData = response.data;
    if (response.config.isSourceData) {
      return resData;
    }
    let { isNotTransformRequestResult } = response.config;
    if (isNotTransformRequestResult) {
      let fileName = "导出文件.xlsx";
      if (response.headers["content-disposition"]) {
        fileName = decodeURIComponent(
          response.headers["content-disposition"]
        ).replace("attachment;filename*=utf-8''", "");
        // .replace(".xlsx", "");
      }
      const link = document.createElement("a");
      const blob = new Blob([resData], {
        type: "application/vnd.ms-excel",
      });
      link.style.display = "none";
      link.href = URL.createObjectURL(blob);
      link.setAttribute("download", fileName);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      ElMessage.success("导出成功");
    }

    // 正常接收数据
    if (resData.code !== "000000" && !isNotTransformRequestResult) {
      ElMessage.error(resData.mesg);
      return false;
    } else {
      return resData.data;
    }
  },
  (error) => {
    let errorStatus = error.response.status;
    if (errorStatus == 401 || errorStatus == 403) {
      return;
    }
    const code = String(error.response.status).substring(0, 1);
    switch (code) {
      case "4":
        ElMessage({
          message: "参数错误,请联系管理员",
          type: "error",
          duration: 3000,
        });
        break;
      case "5":
        ElMessage({
          message: error.response.data.error,
          type: "error",
          duration: 3000,
        });
        break;
      default:
        // 报错统一提示
        ElMessage({
          message: "Error",
          type: "error",
          duration: 3000,
        });
        break;
    }
  }
);

export default $axios;
